<template>
  <div class="worker-profile">
    <div class="back-button">
      <el-button icon="el-icon-back" link @click="goBack">返回主页</el-button>
    </div>
    
    <div class="profile-header">
      <div class="avatar-container">
        <el-avatar :size="100" :src="avatarUrl" @error="handleAvatarError">
          <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
        </el-avatar>
        <div class="upload-btn">
          <el-upload
            class="avatar-uploader"
            action="/api/workerProfile/uploadAvatar"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </div>
      </div>
      <div class="worker-info">
        <h2>{{ workerInfo.nickname || workerInfo.workerName || '维修工' }}</h2>
        <p class="skill-level">{{ getSkillLevelName(profile.skillLevel) }}</p>
        <p class="signature">{{ profile.signature || '专业维修，用心服务' }}</p>
      </div>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本资料" name="basic">
        <el-form :model="profile" ref="profileForm" label-width="100px" :rules="rules">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profile.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">保密</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="profile.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="个性签名" prop="signature">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="写一句话介绍自己"
              v-model="profile.signature">
            </el-input>
          </el-form-item>
          
          <el-form-item label="工作年限" prop="workYears">
            <el-input-number v-model="profile.workYears" :min="0" :max="50"></el-input-number>
          </el-form-item>
          
          <el-form-item label="技能等级" prop="skillLevel">
            <el-select v-model="profile.skillLevel" placeholder="请选择技能等级">
              <el-option
                v-for="level in skillLevels"
                :key="level.level"
                :label="level.name"
                :value="level.level">
                <span>{{ level.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ level.description }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="专长领域" prop="specializations">
            <el-select
              v-model="selectedSpecializations"
              multiple
              filterable
              placeholder="请选择专长领域">
              <el-option
                v-for="item in specializationOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="工作地点偏好" prop="locationPreference">
            <el-input v-model="profile.locationPreference" placeholder="请输入工作地点偏好"></el-input>
          </el-form-item>
          
          <el-form-item label="证书与资质" prop="certifications">
            <div class="cert-list">
              <div 
                v-for="(cert, index) in certifications" 
                :key="index" 
                class="cert-item">
                <el-input v-model="cert.name" placeholder="证书名称"></el-input>
                <el-date-picker
                  v-model="cert.date"
                  type="date"
                  placeholder="获取日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD">
                </el-date-picker>
                <el-button 
                  type="danger" 
                  icon="el-icon-delete" 
                  circle 
                  @click="removeCertification(index)">
                </el-button>
              </div>
              <el-button type="primary" icon="el-icon-plus" @click="addCertification">添加证书</el-button>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveProfile">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
      <el-tab-pane label="维修历史" name="repairs">
        <div class="empty-data" v-if="!repairRecords.length">
          <el-empty description="暂无维修记录"></el-empty>
        </div>
        <div v-else>
          <el-table
            :data="repairRecords"
            style="width: 100%">
            <el-table-column
              prop="orderId"
              label="订单号"
              width="180">
            </el-table-column>
            <el-table-column
              prop="repairType"
              label="维修类型">
            </el-table-column>
            <el-table-column
              prop="repairDate"
              label="维修日期"
              width="180">
            </el-table-column>
            <el-table-column
              label="状态">
              <template slot-scope="scope">
                <el-tag :type="getTagType(scope.row.statusCode)">
                  {{ getStatusText(scope.row.statusCode) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button 
                  @click="viewOrderDetail(scope.row)" 
                  type="text" 
                  size="small">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="技能成长" name="skills">
        <div class="skill-growth">
          <el-card class="skill-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>当前技能等级</span>
            </div>
            <div class="skill-progress">
              <el-progress 
                :percentage="getSkillPercentage(profile.skillLevel)" 
                :status="getSkillProgressStatus(profile.skillLevel)">
              </el-progress>
              <div class="level-name">{{ getSkillLevelName(profile.skillLevel) }}</div>
              <div class="level-description">{{ getSkillLevelDescription(profile.skillLevel) }}</div>
            </div>
            
            <div class="skill-tips" v-if="profile.skillLevel < 3">
              <h4>提升技能等级的方法：</h4>
              <ul>
                <li>完成更多的维修订单</li>
                <li>提高客户满意度评分</li>
                <li>获取更多专业证书</li>
                <li>参加系统培训课程</li>
              </ul>
            </div>
            
            <div class="skill-tips" v-else>
              <h4>恭喜您已达到最高技能等级！</h4>
              <p>您可以担任新维修工的导师，分享您的经验和知识。</p>
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加修改密码对话框 -->
    <el-button type="primary" @click="showChangePasswordDialog" class="change-password-btn">
      修改密码
    </el-button>

    <el-dialog
      title="修改密码"
      v-model="changePasswordVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="100px"
        class="password-form"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
            placeholder="请输入原密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changePasswordVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitChangePassword">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'WorkerProfile',
  data() {
    // 验证确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    
    return {
      activeTab: 'basic',
      profile: {
        openid: '',
        avatar: '',
        gender: 0,
        birthday: '',
        signature: '',
        skillLevel: 1,
        workYears: 0,
        specializations: '',
        certifications: '',
        locationPreference: '',
      },
      workerInfo: {
        nickname: '',
        workerName: '',
        workerPhone: '',
        workerEmail: '',
      },
      rules: {
        workYears: [
          { type: 'number', required: true, message: '请输入工作年限', trigger: 'blur' }
        ],
        skillLevel: [
          { required: true, message: '请选择技能等级', trigger: 'change' }
        ],
      },
      repairRecords: [],
      avatarUrl: '',
      skillLevels: [],
      specializationOptions: [],
      selectedSpecializations: [],
      certifications: [],
      
      // 修改密码相关数据
      changePasswordVisible: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getWorkerProfile();
    this.getWorkerInfo();
    this.getRepairRecords();
    this.getSkillLevelInfo();
    this.getSpecializations();
  },
  computed: {
    // 动态获取头像上传认证头
    uploadHeaders() {
      const loginType = localStorage.getItem("currentLoginType") || 'worker';
      const satoken = localStorage.getItem(`satoken_${loginType}`);
      return {
        'satoken': satoken || '',
        'loginType': loginType
      };
    }
  },
  methods: {
    async getWorkerProfile() {
      try {
        // 确保使用正确的路径 + 记录详细日志信息
        console.log("开始请求维修工个人资料，当前登录类型:", localStorage.getItem("currentLoginType"));
        console.log("token:", localStorage.getItem(`satoken_${localStorage.getItem("currentLoginType")}`));
        
        // 尝试从localStorage获取维修工信息，提取openid
        const workerInfoStr = localStorage.getItem(`userInfo_worker`);
        let workerOpenid = '';
        if (workerInfoStr) {
          try {
            const workerInfo = JSON.parse(workerInfoStr);
            workerOpenid = workerInfo.openid || '';
            console.log("从localStorage获取的维修工openid:", workerOpenid);
          } catch (e) {
            console.error("解析localStorage中的维修工信息失败:", e);
          }
        }
        
        // 尝试直接请求API获取个人资料
        const res = await axios.get('/workerProfile/getWorkerProfile');
        console.log("维修工个人资料请求响应:", res);
        
        if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
          this.profile = res.data.data || this.getDefaultProfile();
          this.avatarUrl = this.profile.avatar || '';
          
          // 处理专长领域JSON
          if (this.profile.specializations) {
            try {
              const specs = JSON.parse(this.profile.specializations);
              this.selectedSpecializations = Array.isArray(specs) ? specs : [];
            } catch (e) {
              console.error('Failed to parse specializations', e);
              this.selectedSpecializations = [];
            }
          }
          
          // 处理证书JSON
          if (this.profile.certifications) {
            try {
              const certs = JSON.parse(this.profile.certifications);
              this.certifications = Array.isArray(certs) ? certs : [];
            } catch (e) {
              console.error('Failed to parse certifications', e);
              this.certifications = [];
            }
          } else {
            this.certifications = [];
          }
        } else {
          console.log('获取维修工个人资料返回非成功状态，尝试备选方案');
          
          // 如果API调用失败，尝试直接使用openid获取
          if (workerOpenid) {
            try {
              const directRes = await axios.get(`/workerProfile/directGetProfile?openid=${workerOpenid}`);
              if (directRes.data && (directRes.data.code === 200 || directRes.data.code === 43000)) {
                this.profile = directRes.data.data || this.getDefaultProfile();
                this.avatarUrl = this.profile.avatar || '';
                
                // 处理专长领域JSON
                if (this.profile.specializations) {
                  try {
                    const specs = JSON.parse(this.profile.specializations);
                    this.selectedSpecializations = Array.isArray(specs) ? specs : [];
                  } catch (e) {
                    console.error('Failed to parse specializations', e);
                    this.selectedSpecializations = [];
                  }
                }
                
                // 处理证书JSON
                if (this.profile.certifications) {
                  try {
                    const certs = JSON.parse(this.profile.certifications);
                    this.certifications = Array.isArray(certs) ? certs : [];
                  } catch (e) {
                    console.error('Failed to parse certifications', e);
                    this.certifications = [];
                  }
                } else {
                  this.certifications = [];
                }
                
                return;
              }
            } catch (e) {
              console.error("直接通过openid获取维修工个人资料失败:", e);
            }
          }
          
          // 使用默认数据
          console.error("获取维修工个人资料失败，使用默认数据");
          this.profile = this.getDefaultProfile();
          this.selectedSpecializations = [];
          this.certifications = [];
        }
      } catch (error) {
        console.error('获取维修工个人资料失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
          console.error('请求头:', error.config && error.config.headers);
          console.error('请求路径:', error.config && error.config.url);
        }
        this.profile = this.getDefaultProfile();
        this.selectedSpecializations = [];
        this.certifications = [];
      }
    },
    
    getDefaultProfile() {
      return {
        openid: '',
        avatar: '',
        gender: 0,
        birthday: '',
        signature: '专业维修，用心服务',
        skillLevel: 1,
        workYears: 0,
        specializations: '',
        certifications: '',
        locationPreference: '',
      };
    },
    async getWorkerInfo() {
      try {
        // 使用已有的workerProfile API，不需要/user_worker_server/api前缀
        const res = await axios.get('/workerProfile/getWorkerProfile');
        if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
          // 从返回的维修工资料中获取基本信息
          this.workerInfo = {
            nickname: this.profile.nickname || localStorage.getItem('nickname') || '维修工',
            workerName: this.profile.workerName || '',
            workerPhone: this.profile.phone || '',
            workerEmail: this.profile.email || ''
          };
        } else {
          this.workerInfo = { nickname: '维修工', workerName: '', workerPhone: '', workerEmail: '' };
        }
      } catch (error) {
        console.error('获取维修工信息失败', error);
        this.workerInfo = { nickname: '维修工', workerName: '', workerPhone: '', workerEmail: '' };
      }
    },
    async getRepairRecords() {
      try {
        console.log("开始获取维修记录");
        const res = await axios.post('/workerHome/queryWorkerOrder', {});
        console.log("维修记录响应:", res);
        if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
          this.repairRecords = res.data.data?.repairOrdersEntities || [];
        } else {
          console.log("获取维修记录返回非成功状态，使用空数组");
          this.repairRecords = [];
        }
      } catch (error) {
        console.error('获取维修记录失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        this.repairRecords = [];
      }
    },
    async getSkillLevelInfo() {
      try {
        console.log("开始获取技能等级信息");
        const res = await axios.get('/workerProfile/getSkillLevelInfo');
        console.log("技能等级信息响应:", res);
        if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
          this.skillLevels = res.data.data || [];
        } else {
          console.log("获取技能等级信息失败，使用默认数据");
          this.skillLevels = this.getDefaultSkillLevels();
        }
      } catch (error) {
        console.error('获取技能等级信息失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        this.skillLevels = this.getDefaultSkillLevels();
      }
    },
    async getSpecializations() {
      try {
        console.log("开始获取专长领域信息");
        const res = await axios.get('/workerProfile/getSpecializations');
        console.log("专长领域信息响应:", res);
        if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
          this.specializationOptions = res.data.data || [];
        } else {
          console.log("获取专长领域信息失败，使用默认数据");
          this.specializationOptions = this.getDefaultSpecializations();
        }
      } catch (error) {
        console.error('获取专长领域信息失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
        }
        this.specializationOptions = this.getDefaultSpecializations();
      }
    },
    
    getDefaultSkillLevels() {
      return [
        { level: 1, name: "初级维修工", description: "能够处理基本维修任务，有基础维修知识" },
        { level: 2, name: "中级维修工", description: "能够处理复杂维修任务，具备丰富的维修经验" },
        { level: 3, name: "高级维修工", description: "能够处理各类疑难问题，并有指导培训其他维修工的能力" }
      ];
    },
    
    getDefaultSpecializations() {
      return [
        { id: "electrical", name: "电气维修" },
        { id: "plumbing", name: "水暖维修" },
        { id: "carpentry", name: "木工维修" },
        { id: "electronics", name: "电子设备维修" },
        { id: "hvac", name: "暖通空调维修" }
      ];
    },
    async saveProfile() {
      try {
        this.$refs.profileForm.validate(async (valid) => {
          if (valid) {
            // 获取维修工ID
            let openid = '';
            
            // 方法1：从localStorage中获取
            const userInfoStr = localStorage.getItem('userInfo_worker');
            if (userInfoStr) {
              try {
                const userInfo = JSON.parse(userInfoStr);
                openid = userInfo.workerid;
                console.log("从localStorage获取的维修工ID:", openid);
              } catch (e) {
                console.error("解析localStorage中的维修工信息失败:", e);
              }
            }
            
            // 方法2：从profile中获取
            if (!openid && this.profile && this.profile.openid) {
              openid = this.profile.openid;
              console.log("从profile获取的维修工ID:", openid);
            }
            
            // 方法3：从URL参数中获取
            if (!openid) {
              const urlParams = new URLSearchParams(window.location.search);
              openid = urlParams.get('openid') || urlParams.get('workerid');
              console.log("从URL参数获取的维修工ID:", openid);
            }
            
            // 创建提交数据对象，只包含需要的字段
            const submitProfile = {
              openid: openid,
              gender: this.profile.gender,
              signature: this.profile.signature,
              skillLevel: this.profile.skillLevel,
              workYears: this.profile.workYears,
              specializations: Array.isArray(this.profile.specializations) ? 
                JSON.stringify(this.profile.specializations) : this.profile.specializations,
              certifications: Array.isArray(this.profile.certifications) ? 
                JSON.stringify(this.profile.certifications) : this.profile.certifications,
              locationPreference: this.profile.locationPreference
            };
            
            // 移除空值
            Object.keys(submitProfile).forEach(key => {
              if (submitProfile[key] === null || submitProfile[key] === undefined || submitProfile[key] === '') {
                delete submitProfile[key];
              }
            });
            
            // 检查是否有数据要提交
            if (Object.keys(submitProfile).length === 0) {
              this.$message.warning('没有要保存的数据');
              return;
            }
            
            // 检查必要字段
            if (!submitProfile.openid) {
              // 如果所有方法都无法获取openid，尝试从后端获取当前用户信息
              try {
                const userRes = await axios.get('/workerHome/getWorkerInfo');
                if (userRes.data && userRes.data.code === 43000 && userRes.data.data) {
                  submitProfile.openid = userRes.data.data.workerid;
                  console.log("从API获取的维修工ID:", submitProfile.openid);
                }
              } catch (error) {
                console.error("获取维修工信息失败:", error);
              }
              
              if (!submitProfile.openid) {
                this.$message.error('维修工ID不能为空，请重新登录');
                return;
              }
            }
            
            console.log("准备保存的维修工个人资料数据:", submitProfile);
            
            try {
              const res = await axios({
                method: 'post',
                url: '/workerProfile/updateProfile',
                data: submitProfile,
                headers: {
                  'Content-Type': 'application/json'
                }
              });
              
              console.log("保存响应:", res);
              
              if (res.data && (res.data.code === 200 || res.data.code === 43000)) {
                this.$message.success('个人资料更新成功');
                this.getWorkerProfile(); // 重新获取用户资料
              } else {
                throw new Error(res.data?.msg || '保存失败');
              }
            } catch (error) {
              console.error("保存失败:", error);
              this.$message.error(error.message || '保存失败，请检查网络连接或联系管理员');
            }
          } else {
            return false;
          }
        });
      } catch (error) {
        console.error('保存个人资料失败', error);
        if (error.response) {
          console.error('错误状态码:', error.response.status);
          console.error('错误数据:', error.response.data);
          console.error('请求URL:', error.config?.url);
          console.error('请求数据:', error.config?.data);
        }
        this.$message.error('保存个人资料失败，请检查网络连接或联系管理员');
      }
    },
    resetForm() {
      this.$refs.profileForm.resetFields();
      this.getWorkerProfile();
    },
    getTagType(status) {
      const statusMap = {
        'TO_ACCEPT': 'warning',
        'HAVE_ACCEPTED': 'primary',
        'WAIT_PAY': 'danger',
        'HAVE_PAID': 'primary',
        'WAIT_FINISHED': 'primary',
        'HAVE_FINISHED': 'success',
        'REJECTED': 'info',
      };
      return statusMap[status] || 'info';
    },
    getStatusText(status) {
      const statusMap = {
        'TO_ACCEPT': '待受理',
        'HAVE_ACCEPTED': '已受理',
        'WAIT_PAY': '待支付',
        'HAVE_PAID': '已支付',
        'WAIT_FINISHED': '待完结',
        'HAVE_FINISHED': '已完结',
        'REJECTED': '已驳回',
      };
      return statusMap[status] || '未知状态';
    },
    getSkillLevelName(level) {
      const skillLevel = this.skillLevels.find(item => item.level === level);
      return skillLevel ? skillLevel.name : '未知等级';
    },
    getSkillLevelDescription(level) {
      const skillLevel = this.skillLevels.find(item => item.level === level);
      return skillLevel ? skillLevel.description : '';
    },
    getSkillPercentage(level) {
      const percentageMap = {
        1: 33,
        2: 66,
        3: 100,
      };
      return percentageMap[level] || 0;
    },
    getSkillProgressStatus(level) {
      const statusMap = {
        1: '',
        2: 'warning',
        3: 'success',
      };
      return statusMap[level] || '';
    },
    viewOrderDetail(order) {
      this.$router.push({
        path: '/repairRecord/details',
        query: { orderId: order.orderId }
      });
    },
    addCertification() {
      this.certifications.push({
        name: '',
        date: '',
      });
    },
    removeCertification(index) {
      this.certifications.splice(index, 1);
    },
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.avatarUrl = res.data;
        this.profile.avatar = res.data;
        this.$message.success('头像上传成功');
      } else {
        // 静默处理头像上传失败，不显示错误信息
        console.log('头像上传失败:', res.msg);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG/PNG/WEBP格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarError() {
      this.avatarUrl = '';
    },
    goBack() {
      // 直接返回首页，不经过pullAllAnnouncement的API调用
      this.$router.replace({path: '/workerHome'});
    },
    
    // 显示修改密码对话框
    showChangePasswordDialog() {
      this.changePasswordVisible = true;
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
    },
    
    // 提交修改密码
    submitChangePassword() {
      this.$refs.passwordFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post('/workerHome/updatePassword', {
              oldPassword: this.passwordForm.oldPassword,
              newPassword: this.passwordForm.newPassword
            });
            
            if (response.data.code === 43000) {
              this.$message.success('密码修改成功！');
              this.changePasswordVisible = false;
            } else {
              this.$message.error(response.data.msg || '密码修改失败');
            }
          } catch (error) {
            this.$message.error('密码修改失败：' + error.message);
          }
        }
      });
    }
  }
}
</script>

<style scoped>
.worker-profile {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 16px;
  min-height: 500px;
  position: relative;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.back-button {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.back-button .el-button {
  transition: all 0.3s ease;
}

.back-button .el-button:hover {
  transform: translateX(-5px);
  color: #409EFF;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 25px;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
  border-radius: 16px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.profile-header::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(64, 158, 255, 0.05) 0%, rgba(255, 255, 255, 0) 70%);
  animation: rotate 15s infinite linear;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.avatar-container {
  margin-right: 30px;
  text-align: center;
  position: relative;
  z-index: 1;
}

.el-avatar {
  border: 4px solid #fff;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.upload-btn {
  margin-top: 15px;
  opacity: 0;
  transform: translateY(10px);
  transition: all 0.3s ease;
}

.avatar-container:hover .upload-btn {
  opacity: 1;
  transform: translateY(0);
}

.worker-info {
  flex-grow: 1;
  position: relative;
  z-index: 1;
}

.worker-info h2 {
  font-size: 24px;
  margin: 0 0 5px;
  color: #303133;
  font-weight: 600;
  transition: all 0.3s ease;
}

.skill-level {
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin: 8px 0;
  padding: 4px 12px;
  background-color: rgba(64, 158, 255, 0.1);
  border-radius: 20px;
  display: inline-block;
  transition: all 0.3s ease;
}

.signature {
  color: #606266;
  font-style: italic;
  margin-top: 8px;
  padding: 8px 15px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 20px;
  display: inline-block;
  border-left: 3px solid #409EFF;
  transition: all 0.3s ease;
}

.el-tabs {
  margin-top: 30px;
  background-color: white;
  padding: 25px;
  border-radius: 16px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.el-form-item {
  margin-bottom: 25px;
  transition: all 0.3s ease;
}

.el-form-item:hover {
  transform: translateX(5px);
}

.el-button {
  border-radius: 8px;
  padding: 12px 20px;
  transition: all 0.3s ease;
}

.el-button--primary {
  background: linear-gradient(135deg, #409EFF 0%, #64b5f6 100%);
  border: none;
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
}

.el-button--primary:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.4);
}

.empty-data {
  padding: 60px 0;
  text-align: center;
  background-color: #fafafa;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.cert-list {
  border: 1px dashed #ccc;
  padding: 20px;
  border-radius: 12px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.cert-list:hover {
  border-color: #409EFF;
  background-color: #f5f9ff;
}

.cert-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.cert-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.cert-item .el-input {
  margin-right: 10px;
}

.cert-item .el-date-picker {
  margin-right: 10px;
}

.cert-item .el-button {
  transition: all 0.3s ease;
}

.cert-item .el-button:hover {
  transform: rotate(90deg);
}

.skill-card {
  margin-bottom: 20px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.skill-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.skill-card .el-card__header {
  background-color: #f5f9ff;
  border-bottom: 1px solid #e6f1ff;
  padding: 15px 20px;
}

.skill-progress {
  padding: 25px 0;
}

.level-name {
  font-size: 20px;
  font-weight: bold;
  margin: 15px 0 10px;
  color: #409EFF;
  transition: all 0.3s ease;
}

.level-description {
  color: #606266;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f9ff;
  border-radius: 8px;
  border-left: 3px solid #409EFF;
  transition: all 0.3s ease;
}

.skill-tips {
  background: #f0f9eb;
  padding: 20px;
  border-radius: 12px;
  margin-top: 25px;
  box-shadow: 0 3px 10px rgba(103, 194, 58, 0.1);
  transition: all 0.3s ease;
}

.skill-tips:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(103, 194, 58, 0.2);
}

.skill-tips h4 {
  color: #67c23a;
  margin-top: 0;
  font-size: 16px;
}

.skill-tips ul {
  padding-left: 20px;
  margin-bottom: 0;
}

.skill-tips ul li {
  margin-bottom: 8px;
  color: #606266;
}

.skill-tips p {
  color: #606266;
  margin-bottom: 0;
}

/* 表格样式优化 */
.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  margin-top: 20px;
}

.el-table th {
  background-color: #f5f9ff !important;
  color: #303133;
  font-weight: 600;
  padding: 12px 0;
}

.el-table td {
  padding: 12px 0;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #f9fafc;
}

.el-table__row {
  transition: all 0.3s ease;
}

.el-table__row:hover > td {
  background-color: #f5f9ff !important;
}

.el-table__row:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  z-index: 2;
}

.el-tag {
  border-radius: 20px;
  padding: 0 12px;
  height: 28px;
  line-height: 26px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    text-align: center;
    padding: 20px 15px;
  }
  
  .avatar-container {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .upload-btn {
    opacity: 1;
    transform: translateY(0);
  }
  
  .el-tabs {
    padding: 15px;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .cert-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .cert-item .el-input,
  .cert-item .el-date-picker {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }
}

.worker-profile {
  .change-password-btn {
    margin-top: 20px;
  }
  
  .password-form {
    padding: 20px;
    
    .el-form-item {
      margin-bottom: 20px;
    }
  }
  
  .dialog-footer {
    text-align: right;
    padding-top: 10px;
  }
}
</style> 